package com.bsoft.ecommerce.filter;

import com.bsoft.ecommerce.constant.CommonConstant;
import com.bsoft.ecommerce.util.TokenParseUtil;
import com.bsoft.ecommerce.vo.LoginUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//用户身份统一登录拦截
@Slf4j
@SuppressWarnings("all")
@Component
public class LoginUserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //部分请求 不需要白名单
         if(checkWhiteListUrl(request.getRequestURI())){
             return true;
         }
        // 先尝试从http  header 里边拿到token
        String token = request.getHeader(CommonConstant.JWT_USER_INFO_KEY);
        LoginUserInfo loginUserInfo=null;
        try {
            loginUserInfo= TokenParseUtil.parseUserInfoFromToken(token);
        } catch (Exception e){
             e.printStackTrace();
        }
        //如果程序走到这里 说明header 中没有 token 信息
        if(null == loginUserInfo) {
            throw new RuntimeException("can not parse current login user");
        }
        log.info("set login user info", request.getRequestURI());
        //设置当前请求上下文
        AccessContext.setLoginUserInfo(loginUserInfo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
     //在请求完全结束调用 常用于清理资源等工作
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
             if(null!= AccessContext.getLoginuserInfo()){
                 AccessContext.clearLogUserInfo();
             }
    }
    // 检验是否是白名单接口
    private boolean checkWhiteListUrl(String url){
           return StringUtils.containsAny(url,"springfox","swagger","v2","webjars","doc.html");
    }
}
